#include "HttpServer.hpp"
#include <memory>
//#define SEP "\r\n"
const static std::string SEP = "\r\n";

// // std::string HttpHandler(const std::string&request)
// // {
// //     std::cout<<request<<std::endl;

// //     std::string response = "HTTP/1.0 200 OK"+SEP;
// //     response+=SEP;
// //     response += "Hello HTTP!";

// //     return response;
// // }
// std::string HttpHandler(const std::string& request)
// {
//     std::cout << request << std::endl;

//     std::string body = "Hello HTTP!";
//     std::string response = "HTTP/1.0 200 OK" + SEP;
//     response += "Content-Length: " + std::to_string(body.size()) + SEP;  // 添加 Content-Length
//     response += "Content-Type: text/plain" + SEP;  // 指定 MIME 类型
//     response += SEP;  // 头部结束
//     response += body; // 添加正文

//     return response;
// }


// int main()
// {
//     std::unique_ptr<HttpServer> ptr(new HttpServer(HttpHandler));
//     ptr->Init();
//     ptr->Start();
//     return 0;
// }

#include <vector>
#include <mutex>

std::vector<std::string> messages; // 存储消息
std::mutex mtx;

std::string handleChatRequest(const std::string &request)
{
    std::lock_guard<std::mutex> lock(mtx);

    // 假设前端 POST 了一条新消息
    if (request.find("POST") == 0)
    {
        size_t pos = request.find("\r\n\r\n");
        if (pos != std::string::npos)
        {
            std::string newMessage = request.substr(pos + 4);
            messages.push_back(newMessage);
        }
        return "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK";
    }

    // 前端 GET 请求，返回所有消息
    std::string responseBody;
    for (const auto &msg : messages)
        responseBody += msg + "\n";

    std::string response = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: " +
                           std::to_string(responseBody.size()) + "\r\n\r\n" + responseBody;
    return response;
}


int main()
{
    std::unique_ptr<HttpServer> ptr(new HttpServer(handleChatRequest));
    ptr->Init();
    ptr->Start();
    return 0;
}
